import axios from "axios";
import router from "../router/index";

// 配置相应时间
axios.defaults.timeout = 60 * 1000;

// 请求拦截
axios.interceptors.request.use(
  config => {
    // 非登录接口不需要传token
    if (config.url.indexOf('login') === -1) {
      config.headers.token = localStorage.getItem('access_token');
    }
    return config;
  },
  error => {return Promise.reject(error);}
  );
axios.interceptors.response.use(
  res => {
    if (res.data.ret === 0) {
      return res;
    // } else if (res.data.ret === 2000) {
    //   router.replace('/login');
    //   return Promise.reject({ data: '登录验证已过期，请重新登陆' });
    } else {
      return Promise.reject(res.data);
    }
  },
  error => {
    if ('response' in error) {
      if (error.response.status === 401) {
        router.replace('/login');
        return Promise.reject({ data: '登录验证已过期，请重新登陆' });
      }
    }
    return Promise.reject(error);
  }
  );

//发送请求
export function fetchGet(url, data) {
  return new Promise((resolve, reject) => {
    axios
      .get(url, {data})
      .then(res => {
        resolve(res.data);
      })
      .catch(err => {
        // this.$message.error(err);
        reject(err)
      });
  })
}

export function fetchPost(url, data) {
  return new Promise((resolve, reject) => {
    axios
      .post(url, data)
      .then(res => {
        resolve(res.data);
      })
      .catch(err => reject(err));
  })
}

export function fetchPut(url, data, params) {
  return new Promise((resolve, reject) => {
    axios
      .put(url, data, {params})
      .then(res => {
        resolve(res.data);
      })
      .catch(err => reject(err));
  })
}

export function fetchDelete(url, params) {
  return new Promise((resolve, reject) => {
    axios
      .delete(url, {params})
      .then(res => {
        resolve(res.data);
      })
      .catch(err => reject(err));
  })
}